import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

interface ImportMetaEnv extends globalThis.ImportMetaEnv {
  VITE_BASE_API: string
}

const serive = axios.create({
  baseURL: (import.meta.env as ImportMetaEnv).VITE_BASE_API,
  timeout: 5000
})

serive.interceptors.request.use(
  config => {
    config.headers['X-Token'] = 'my-token'
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

serive.interceptors.response.use(
  response => {
    // ...返回成功失败的做法
    const res = response.data
    
    if (res.code !== 200) {
      ElMessage.error({
        type: 'error',
        message: res.error ?? 'Error',
        duration: 5 * 1000
      })

      if (res.code === 5 || res.code === 3 || res.code === '4') {
        ElMessageBox.confirm('您已登出，请重新登录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        })
      }

      return Promise.reject(new Error(res.messsage ?? 'Error'))
    } else {
      return res
    }
  },
  error => {
    // ...返回失败的做法
    return Promise.reject(error)

  }
)

export default serive